package com.android.lovely.ui.viewmodel

import android.content.Context
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import androidx.core.os.ConfigurationCompat
import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.systemService
import com.android.lovely.api.service.upload
import com.android.lovely.api.service.userService
import com.android.lovely.data.UserBean
import com.android.lovely.ext.getPhoneName
import com.android.lovely.ext.getTimeZone
import com.android.lovely.ext.isVPNConnected
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.UIController.dismissLoading
import com.android.lovely.framework.UIController.showLoading
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.manager.KVStore
import com.android.lovely.user.UserManager
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.doOnIO
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.withContext
import java.util.Locale

/**
 *
 * @author why
 * @date 2025/3/8 20:21
 */
class LoginViewModel : BaseViewModel() {

    private val _userLogin = MutableSharedFlow<UserBean>(extraBufferCapacity = 1)
    val userLogin: SharedFlow<UserBean> get() = _userLogin


    fun guestLogin(onNext: (Boolean) -> Unit) {
        showLoading(false)
        viewModelScope.launchSafety {
            doContinuousOperation(3) {
                val loginRsp = userService.signIn(getLoginParam())
                val token = loginRsp["token"] as? String ?: ""
                saveToken(token)
            }
        }.onError {
            onNext(false)
            dismissLoading()
        }.onComplete {
            onNext(true)
            dismissLoading()
        }
    }

    fun login(email: String, password: String,onNext: (Boolean) -> Unit) {
        showLoading(false)
        viewModelScope.launchSafety {
            doContinuousOperation(3) {
                val loginRsp = userService.signIn(
                    getLoginParam(
                        platform = "email",
                        email = email,
                        password = password
                    )
                )
                val token = loginRsp["token"] as? String ?: ""
                saveToken(token)
            }
        }.onError {
            onNext(false)
            dismissLoading()
        }.onComplete {
            onNext(true)
            dismissLoading()
        }
    }

    private suspend fun saveToken(token: String) {
        KVStore.token = token
        val user = userService.refreshUser()
        UserManager.userInfo = user
        getConfig()
        onNext(user)
    }

    private suspend fun onNext(user: UserBean) {
        if (KVStore.firebase.isNotEmpty()) {
            applicationScope.launchSafety {
                UserManager.updateAuth()
            }
        }
        user.fcmTag.forEach {
            Firebase.messaging.subscribeToTopic(it)
        }
        _userLogin.emit(user)
    }

    private suspend fun getConfig() = withContext(Dispatchers.IO) {
        val config = systemService.getSystemConfig()
        KVStore.system = config
    }


    private fun getLoginParam(
        email: String = "", password: String = "", platform: String = "visitor"
    ): Map<String, Any> {
        return mapOf(
            "third_token" to "",
            "third_platform" to platform,
            "email" to email,
            "password" to password,
            "d_name" to getPhoneName(),
            "third_did" to Settings.Secure.getString(
                appContext.contentResolver,
                Settings.Secure.ANDROID_ID
            ),
            "sim_country" to (appContext.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager)?.simCountryIso.orEmpty(),
            "is_vpn" to if (isVPNConnected()) 1 else 0,
            "d_model" to Build.MODEL,
            "lang" to (ConfigurationCompat.getLocales(Resources.getSystem().configuration)
                .get(0)?.language ?: Locale.getDefault().language ?: "en").lowercase(),
            "sys_version" to Build.VERSION.RELEASE,
            "referrer" to KVStore.refers,
            "timezone" to getTimeZone(),
        )
    }

    fun updateUserInfo(currentName: String, gender: Int, uri: Uri?, onNext: () -> Unit = {}) {
        viewModelScope.launchWithLoading {
            val avatar = uri?.upload() ?: UserManager.userInfo?.headImg.orEmpty()
            UserManager.updateAuth {
                nickname = currentName
                this.avatar = avatar
                this.gender = gender
            }
            onNext.invoke()
        }
    }

    fun saveProfile(botId: Int,currentName: String? , gender: Int, desc: String?, onNext: () -> Unit = {}) {
        viewModelScope.launchWithLoading {
            userService.saveChatInfo(
                mapOf(
                    "bot_id" to botId,
                    "chat_name" to currentName,
                    "chat_gender" to gender,
                    "chat_dec" to desc)
            )
            onNext.invoke()
        }
    }
}